$(function() {
	$("#login_btn").click(function() {
		var username = $("#username_input").val().trim();
		var code = $("#password_input").val().trim();
		//必须提前让input 失去焦点，不然可能又重新打开软键盘 blur之后不能立即触发 click 加 settimeout 或者访问服务
		$("input").blur();

		setTimeout(function() {
			//			if(username == "" || code == "") {
			//				mui.alert("请输入用户名和验证码！", "提示");
			//				return;
			//			} else {
			//				userlogin(username, code)
			//			}

			mui.openWindow({
				url: "index.html",
				id: "index.html",
				extras: {
					param: {
						id: '2',
						username: '李成仁',
						phoneNumber: '13917879498',
						logname: 'lichengren'
					}
				}
			});

		}, 100)
	});

	var countdown = 0;
	$("#verificationCodeBtn").click(function() {
		event.preventDefault();
		if(countdown != 0) {
			event.preventDefault();
			return;
		}
		var url = getServletUrl("LoginServlet");
		var username = $("#username_input").val().trim();
		$.ajax({
			type: "POST",
			url: url,
			data: {
				commdCode: "sendCode",
				userName: username
			},
			dataType: "json",
			success: function(data) {
				if(data.type == 1) {
					countdown = 60;
					settime($('#verificationCodeBtn'));
				} else {
					mui.alert("用户名不存在", "提示");
				}
			},
			error: function(xhr, type, errorThrown) {
				mui.alert("服务器连接失败，请联系管理员！", "提示");
			}
		});
	});

	function settime(obj) { //发送验证码倒计时
		if(countdown == 0) {
			$('#verificationCodeBtn').removeAttr("disabled");
			obj[0].innerHTML = "获取验证码";
			countdown = 60;
			return;
		} else {
			obj[0].innerHTML = "重新发送(" + countdown + ")";
			countdown--;
		}
		setTimeout(function() {
			settime(obj);
		}, 1000)
	}

});
var userlogin = function(username, code) {
	var url = getServletUrl("LoginServlet");
	$.ajax({
		type: "POST",
		url: url,
		data: {
			commdCode: "userLogin",
			userName: username,
			identifyCode: code
		},
		dataType: "json",
		success: function(data) {
			if(data.type != 1) {
				mui.alert("用户名或验证码不正确", "提示");
			} else {
				plus.storage.removeItem("username");
				plus.storage.setItem("username", username);
				plus.storage.removeItem("code");
				plus.storage.setItem("code", code);
				mui.openWindow({
					url: "index.html",
					id: "index.html",
					extras: {
						param: data.tag
					}
				});
			}
		},
		error: function(xhr, type, errorThrown) {
			mui.alert("服务器连接失败，请联系管理员！", "提示");
		}
	});
};